package com.gzcstec.product.controller;

import com.gzcstec.product.dataobject.ProductCategory;
import com.gzcstec.product.dataobject.ProductInfo;
import com.gzcstec.product.service.CategoryService;
import com.gzcstec.product.service.ProductService;
import com.gzcstec.product.utils.ResultUtils;
import com.gzcstec.product.vo.ProductInfoVO;
import com.gzcstec.product.vo.ProductVO;
import com.gzcstec.product.vo.ResultVO;
import com.gzcstec.product.dataobject.DecreaseStockInput;
import com.gzcstec.product.dataobject.ProductInfoOutput;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 1.获取上架商品
     * 2.根据类目类型查找类目
     * 3.拼接数据
     */
    @GetMapping("/list")
    public ResultVO<List<ProductVO>> list() {
        //获取在架商品
        List<ProductInfo> productInfoList = productService.findUpAll();

        //获取在架商品类目
        List<Integer> categoryTypeList =
                productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());

        //获取商品类目信息
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);

        //遍历商品类目
        List<ProductVO> productVOList = new ArrayList<>();
        ProductVO productVO = null;
        for(ProductCategory category : productCategoryList) {
            productVO = new ProductVO();
            productVO.setCategoryName(category.getCategoryName());
            productVO.setCategoryType(category.getCategoryType());

            //遍历商品
            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            ProductInfoVO productInfoVO = null;
            for(ProductInfo productInfo : productInfoList) {
                if(category.getCategoryType().equals(productInfo.getCategoryType())) {
                    productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo , productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }

            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }

        return ResultUtils.success(productVOList);
    }

    @PostMapping("/listForOrder")
    public List<ProductInfoOutput> listForOrder(@RequestBody List<String> productList) {
        return productService.list(productList);
    }

    @PostMapping("/decreaseStock")
    public void decreaseStockForOrder(@RequestBody List<DecreaseStockInput> cartDTOList) {
        productService.decreaseStock(cartDTOList);
    }



}
